package com.smartinput.security

import com.smartinput.user.domain.model.User
import com.smartinput.user.domain.repository.UserRepository
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.security.core.userdetails.UserDetailsService
import org.springframework.security.core.userdetails.UsernameNotFoundException
import org.springframework.stereotype.Service

@Service
class CustomUserDetailsService(
    private val userRepository: UserRepository
) : UserDetailsService {

    override fun loadUserByUsername(username: String): UserDetails {
        val user = userRepository.findByUserName(username)
            ?: throw UsernameNotFoundException("用户不存在: $username")
        
        return createUserDetails(user)
    }

    fun loadUserById(userId: String): UserDetails {
        val user = userRepository.findById(userId)
            .orElseThrow { UsernameNotFoundException("用户不存在: $userId") }
        
        return createUserDetails(user)
    }

    private fun createUserDetails(user: User): UserDetails {
        return org.springframework.security.core.userdetails.User.builder()
            .username(user.uid) // 使用userId作为username，与JWT中的subject一致
            .password(user.password)
            .authorities(listOf(SimpleGrantedAuthority("USER")))
            .build()
    }
} 